package com.kanavi.dataAccess.config;

import com.kanavi.dataAccess.config.anno.ApiAuth;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Component
@Aspect
@Slf4j
public class ApiAuthAspect {

  @Pointcut("@annotation(com.kanavi.dataAccess.config.anno.ApiAuth)")
  private void cutPoint() {}

  @Before("cutPoint()")
  public void before(JoinPoint joinPoint) throws Throwable {
    ApiAuthContextHolder.init();
    ApiAuthContextHolder.getAuthEntity().setIsAuth(true);
    MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
    Method method = methodSignature.getMethod();
    log.info(joinPoint.getSignature().toString() + "::: 开始权限！");
    ApiAuth annotation = method.getAnnotation(ApiAuth.class);
    Class<? extends AbstractApiAuthParamsParser> paramsParser = annotation.paramsParser();
    ApiAuthContextHolder.getAuthEntity().setParamsParser(paramsParser.newInstance());
  }

  @After("cutPoint()")
  public void after(JoinPoint joinPoint) throws Throwable {
    log.info(joinPoint.getSignature().toString() + "::: 结束权限！");
  }
}
